//
//  UIImage+file.swift
//  JoTravel
//
//  Created by tong on 15/10/26.
//  Copyright © 2015年 zhuxietong. All rights reserved.
//

import Foundation
import UIKit


private let img_dir = "tempImgs"
extension UIImage
{
    
    public class func imageWithColor(color:UIColor)  -> UIImage{
        let rect:CGRect = [0.0, 0.0, 1.0, 1.0]
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    public class func image(color:UIColor,frame:CGRect)  -> UIImage{
        UIGraphicsBeginImageContext(frame.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(frame)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
 
}


extension UIImage
{
    
    private static var _index = 0
    public func saveToTemp() ->(path:String,name:String)
    {
        UIImage.createImgDir()
        UIImage._index = UIImage._index + 1
        let name =  "ios_" + Date()["YYYYMMddHHmmss"] + "\((UIImage._index + 1))" + ".png"
        let path = UIImage.getImgDir() + "/" +  name
        
        
        
//        ((try? self.jpegData(compressionQuality: 1.0)?.write(to: URL(fileURLWithPath: path), options: [.atomic])) as ()??)
        ((try? self.pngData()?.write(to: URL(fileURLWithPath: path), options: [.atomic])) as ()??)

        return (path,name)
    }
    
    public class func clearTempDir()
    {
        let fileManager = FileManager.default
        //        let myDirectory = NSHomeDirectory() + "/Documents/Files"
        let myDirectory = UIImage.getImgDir()
        guard let fileArray = fileManager.subpaths(atPath: myDirectory) else {return}
        
        for fn in fileArray{
            do {
                try fileManager.removeItem(atPath: myDirectory + "/\(fn)")
            } catch {
                
            }
//            try! fileManager.removeItem(atPath: myDirectory + "/\(fn)")
        }
    }
    
    
    
    
    
    public class func getImgDir()->String{
        let path:Array = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,FileManager.SearchPathDomainMask.userDomainMask,true)
        return (path[0] as String) + "/\(img_dir)"
        
        //        let path = Bundle.main.path(forResource: "preview", ofType: "html", inDirectory:"html/template")
        //        var ps = path!.components(separatedBy: "/")
        //        ps.removeLast()
        //        let new_path = ps.joined(separator: "/")
        //        return new_path
        
        
        
    }
    
    @discardableResult
    class func createImgDir() ->Bool
    {
        
        let fileManager = FileManager.default
        var isDir : ObjCBool = false
        if fileManager.fileExists(atPath: UIImage.getImgDir(), isDirectory:&isDir) {
            if isDir.boolValue {
                //             debugPrint("file exists and is a directory")
                return true
            } else {
                //             debugPrint("file exists and is not a directory")
                return true
                // file exists and is not a directory
            }
        } else {
            //            debugPrint("file does not exist")
        }
        
        do{
            
            let path = UIImage.getImgDir()
            try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
        }
        catch{
            //            debugPrint("create directory \(error)")
            return false
        }
        return true
    }
    
    
    
    
}
extension UIImage
{
    
    public func commpress(maxSize:Int) ->UIImage
    {
        let source_image = self
        var newSize:CGSize = [source_image.size.width, source_image.size.height]
        let tempHeight = newSize.height/1024
        let tempWidth = newSize.width/1024
        
        if (tempWidth > 1.0 && tempWidth > tempHeight) {
            newSize = [source_image.size.width / tempWidth, source_image.size.height / tempWidth]
        }
        else if (tempHeight > 1.0 && tempWidth < tempHeight){
            newSize = [source_image.size.width / tempHeight, source_image.size.height / tempHeight]
        }
        
        UIGraphicsBeginImageContext(newSize);
        
        source_image.draw(in: [0,0,newSize.width,newSize.height])
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        let imageData = newImage?.jpegData(compressionQuality: 1)
        
        let sizeOrigin = imageData?.count
        let sizeOriginKB = sizeOrigin! / 1024
        
        if (sizeOriginKB > maxSize)
        {
            let finallImageData = newImage!.jpegData(compressionQuality: 0.50)
            
            return UIImage(data: finallImageData!)!
        }
        return UIImage(data: imageData!)!
    
    }
    
    public var net_image:UIImage
        {
        get{
            
            let o_size = self.size
            var width:CGFloat = o_size.width
            var height:CGFloat = o_size.height
            
            let limit_s:CGFloat = 800
            if o_size.width > limit_s
            {
                width = limit_s
                height =  width / (o_size.width/o_size.height)
            }
            if height > limit_s
            {
                height = limit_s
                width = height / (o_size.height/o_size.width)
            }
            
            
            UIGraphicsBeginImageContext(CGSize(width: width, height: height))
            let rc:CGRect = [0,0,width,height]
            self.draw(in: rc)
            let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
            
            //            UIGraphicsEndImageContext()
            let image_data = thumbImage!.jpegData(compressionQuality: 0.50)
            //            let d = UIImagePNGRepresentation(thumbImage)

            
            return UIImage(data: image_data!)!
        }
        
    }
    public func png_commpress(limit:CGFloat = 500)->UIImage
    {
            let o_size = self.size
            var width:CGFloat = o_size.width
            var height:CGFloat = o_size.height
            
        print("+++++___DDSS___\(width)==dd==\(limit)")
            if o_size.width > limit
            {
                width = limit
                height =  width / (o_size.width/o_size.height)
            }
            if height > limit
            {
                height = limit
                width = height / (o_size.height/o_size.width)
            }
                        
            UIGraphicsBeginImageContext(CGSize(width: width, height: height))
            let rc:CGRect = [0,0,width,height]
            self.draw(in: rc)
            let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
            //            UIGraphicsEndImageContext()
        if let img = thumbImage{
            return UIImage(data: img.pngData()!) ?? UIImage()
        }

//            let image_data = thumbImage!.jpegData(compressionQuality: 0.50)
            //            let d = UIImagePNGRepresentation(thumbImage)
        return UIImage()
        
        
    }
    
    public func commpress(width:CGFloat)->UIImage?
    {
        
//        let o_size = self.size
        let scale:CGFloat = self.size.height / self.size.width
        let height:CGFloat = scale * width
            
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        let rc:CGRect = [0,0,width,height]
        self.draw(in: rc)
        let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
        return thumbImage
//
//            //            UIGraphicsEndImageContext()
//
//            let image_data = thumbImage!.jpegData(compressionQuality: 0.50)
//            //            let d = UIImagePNGRepresentation(thumbImage)
//
//
//            return UIImage(data: image_data!)!

        
    }
    
    //    func scaleCompress(image: UIImage!, scale: CGFloat) -> UIImage {
    //        UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scale,image.size.height * scale));
    //        image.drawInRect(CGRectMake(0, 0, image.size.width * scale, image.size.height * scale))
    //        let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    //        UIGraphicsEndImageContext();
    //        return scaledImage
    //    }
    
    
    func pngImg() ->UIImage
    {
        let data = self.pngData()
        return UIImage(data: data!)!
    }
    
}
